<template>
  <div>
    <Navbar />
    <div class="classify">
      <!-- 左侧导航 -->
      <div class="classify-list">
        <van-sidebar v-model="active">
          <van-sidebar-item
            v-for="(item, index) in classifyList"
            :title="item.name"
            :key="item.id"
            @click="handleClassify(index)"
          />
        </van-sidebar>
      </div>
      <!-- 右侧分类展示 -->
      <div id="classify-container">
        <div
          v-for="(item, index) in classifyList"
          :key="item.id"
          class="single"
          :id="'scroll' + index"
        >
          <SingleClassify :classify="item" />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onDeactivated } from 'vue';
import { storeToRefs } from 'pinia';
import useGoodStore from '@/stores/good';
import SingleClassify from './components/SingleClassify.vue';
import Navbar from '@/components/navBar/Navbar.vue';
const goodStore = useGoodStore();
goodStore.getClassify();
const { classifyList } = storeToRefs(goodStore);
onMounted(() => {
  // 监听滚动条位置
  window.addEventListener('scroll', handleScroll, true);
});
//路由不缓存，且路由失活时移除监听，避免点击进入详情后报错
onDeactivated(() => {
  console.log(11111);
  window.removeEventListener('scroll', handleScroll, true);
});
const active = ref(0);
//右侧滚动联动左侧
const handleScroll = () => {
  let scrollTop = document.querySelector('#classify-container').scrollTop;
  for (let i = 0; i < classifyList.value.length; i++) {
    //这里的50根据实际体验去调整
    if (document.querySelector('#scroll' + i).offsetTop - 70 < scrollTop) {
      active.value = i;
    }
  }
};
//左侧菜单点击联动右侧
const handleClassify = (index) => {
  active.value = index;
  let navPage = document.querySelector('#scroll' + index);
  document.querySelector('#classify-container').scrollTop =
    navPage.offsetTop - 50;
};
</script>

<style lang="scss" scoped>
.classify {
  //给顶部导航栏留的安全区域
  margin-top: 10px;
  //这里的40px到时候上面的函数就得写40
  height: calc(100vh - 46px - 50px);
  display: flex;
  .classify-list {
    flex: 1;
    --van-sidebar-width: 100% !important;
    :deep(.van-sidebar-item--select) {
      color: #1989fa;
    }
  }
  #classify-container {
    flex: 4;
    overflow-y: scroll;
    .single {
      h1 {
        height: 15vh;
      }
    }
  }
}
</style>
